package androidx.core.app;

import android.app.job.JobParameters;
import android.app.job.JobServiceEngine;
import android.app.job.JobWorkItem;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;

import androidx.annotation.RequiresApi;

/**
 * Created by Android Studio.
 * User: wsl
 * Date: 2021/12/7
 * Time: 2:36 下午
 * Description:
 */

@RequiresApi(26)
public class SafeJobServiceEngineImpl extends JobServiceEngine implements JobIntentService.CompatJobEngine {
    static final String TAG = "JobServiceEngineImpl";
    static final boolean DEBUG = false;
    final JobIntentService mService;
    final Object mLock = new Object();
    JobParameters mParams;

    SafeJobServiceEngineImpl(JobIntentService service) {
        super(service);
        this.mService = service;
    }

    public IBinder compatGetBinder() {
        return this.getBinder();
    }

    public boolean onStartJob(JobParameters params) {
        this.mParams = params;
        this.mService.ensureProcessorRunningLocked(false);
        return true;
    }

    public boolean onStopJob(JobParameters params) {
        boolean result = this.mService.doStopCurrentWork();
        synchronized(this.mLock) {
            this.mParams = null;
            return result;
        }
    }

    public JobIntentService.GenericWorkItem dequeueWork() {
        JobWorkItem work = null;
        synchronized(this.mLock) {
            if (this.mParams == null) {
                return null;
            }

            try {
                work = this.mParams.dequeueWork();
            } catch (SecurityException var5) {
                var5.printStackTrace();
            }
        }

        if (work != null) {
            work.getIntent().setExtrasClassLoader(this.mService.getClassLoader());
            return new SafeJobServiceEngineImpl.WrapperWorkItem(work);
        } else {
            return null;
        }
    }

    final class WrapperWorkItem implements JobIntentService.GenericWorkItem {
        final JobWorkItem mJobWork;

        WrapperWorkItem(JobWorkItem jobWork) {
            this.mJobWork = jobWork;
        }

        public Intent getIntent() {
            return this.mJobWork.getIntent();
        }

        public void complete() {
            synchronized(SafeJobServiceEngineImpl.this.mLock) {
                if (SafeJobServiceEngineImpl.this.mParams != null) {
                    try {
                        SafeJobServiceEngineImpl.this.mParams.completeWork(this.mJobWork);
                    } catch (SecurityException  | IllegalArgumentException var4) {
                        // 2 这里我们也对completeWork进行了try/catch操作
                        var4.printStackTrace();
                    }
                }
            }
        }
    }
}